﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebAppAuthAdmin.AuthApiManagementServiceReference;
using Web.Framework;
using WebAppAuthAdmin.Code;
using AuthApi.Contracts;
using WebAppAuthAdmin.Code.Security;

namespace WebAppAuthAdmin.App
{
    public partial class ApplicationEdit : BasePage
    {
        private WebApplicationInfo applicationInfo
        {
            get
            {
                return (WebApplicationInfo)ViewState["webApplicationInfo"];
            }
            set
            {
                ViewState["webApplicationInfo"] = value;
            }
        }

        private List<LinkButton> actionButtons = new List<LinkButton>();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            LinkButton crearContactoButton = new LinkButton();
            crearContactoButton.ID = "guardar";
            crearContactoButton.Text = "Guardar";
            crearContactoButton.Click += new EventHandler(lnkGuardar_Click);
            actionButtons.Add(crearContactoButton);

            LinkButton agregarOperacionButton = new LinkButton();
            agregarOperacionButton.ID = "agregarOperacion";
            agregarOperacionButton.Text = "Agregar Operación";
            agregarOperacionButton.Click += new EventHandler(lnkAgregarOperacion_Click);
            actionButtons.Add(agregarOperacionButton);

            LinkButton agregarRolButton = new LinkButton();
            agregarRolButton.ID = "agregarRole";
            agregarRolButton.Text = "Agregar Rol";
            agregarRolButton.Click += new EventHandler(lnkAgregarRole_Click);
            actionButtons.Add(agregarRolButton);

            LinkButton verUsuariosButton = new LinkButton();
            verUsuariosButton.ID = "verUsuarios";
            verUsuariosButton.Text = "Ver Usuarios";
            verUsuariosButton.Click += new EventHandler(verUsuariosButton_Click);
            actionButtons.Add(verUsuariosButton);

            LinkButton crearUsuariosButton = new LinkButton();
            crearUsuariosButton.ID = "crearUsuarios";
            crearUsuariosButton.Text = "Crear Usuario";
            crearUsuariosButton.Click += new EventHandler(lnkCrearUsuario_Click);
            actionButtons.Add(crearUsuariosButton);

            base.LoadContextActions(actionButtons);
        }

        protected override void ApplySecurity()
        {
            bool hasPermision;
            if (applicationInfo.Id == 0)
            {
                hasPermision = HasPermissionFor(AppSecurity.APP_CREATE);               
            }
            else
            {
                hasPermision = HasPermissionFor(AppSecurity.APP_EDIT_ID_ + applicationInfo.Id.ToString());
            }

            this.lnkGuardar.Visible = hasPermision;
            actionButtons.Where(a => a.ID == "guardar").Single().Visible = hasPermision;

            bool hasOperationCrear = HasPermissionFor(AppSecurity.APP_OPERATION_CREAR);
            bool hasRoleCrear = HasPermissionFor(AppSecurity.APP_ROLE_CREAR);
            bool hasUsuarioVer =  HasPermissionFor(AppSecurity.APP_VIEW_USERS_ID_ + applicationInfo.Id.ToString());
            bool hasUsuarioCrear = HasPermissionFor(AppSecurity.APP_USER_CREATE);

            actionButtons.Where(a => a.ID == "agregarOperacion").Single().Visible = hasOperationCrear;
            actionButtons.Where(a => a.ID == "agregarRole").Single().Visible = hasRoleCrear;
            actionButtons.Where(a => a.ID == "verUsuarios").Single().Visible = hasUsuarioVer;
            actionButtons.Where(a => a.ID == "crearUsuarios").Single().Visible = hasUsuarioCrear;

            this.lnkAgregarOperacion.Visible = hasOperationCrear;
            this.lnkAgregarRole.Visible = hasRoleCrear;

            this.GridRoles.Columns[0].Visible = HasPermissionFor(AppSecurity.APP_ROLE_EDITAR);
            this.GridRoles.Columns[1].Visible = HasPermissionFor(AppSecurity.APP_OPERATION_EDITAR);
        }

        protected void Page_Load(object sender, EventArgs e)
        {            
            try
            {
                if (!this.IsPostBack)
                {
                    if (this.Request.QueryString["Id"] == null)
                    {
                        // entidad nueva
                        applicationInfo = new WebApplicationInfo();                        
                    }
                    else
                    {
                        // entidad vieja
                        applicationInfo = WebServiceHelper.GetApplicationById(Convert.ToInt32(this.Request.QueryString["Id"]));
                        HasPermissionToSeeMe(AppSecurity.APP_VIEW_ID_ + applicationInfo.Id.ToString());
                    }

                    Bind();
                }

                if (applicationInfo.Id != 0)
                {
                    HasPermissionToSeeMe(AppSecurity.APP_VIEW_ID_ + applicationInfo.Id.ToString());
                }
                else
                {
                    HasPermissionToSeeMe(AppSecurity.APP_CREATE + applicationInfo.Id.ToString());
                }

                this.pnlDetails.Visible = applicationInfo.Id != default(int);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void Bind()
        {
            if (applicationInfo.Id != 0)          
            {
                this.txtCodigo.Text = Convert.ToString(applicationInfo.Id);
                this.txtCodigo.CssClass = "readonly";
                this.txtCodigo.ReadOnly = true;                
            }

            this.pnlRequiereLoginSinEmpresa.CssClass = this.applicationInfo.RequiereLoginSinEmpresa ? string.Empty : "displayNone";
            this.chkRequireLoginSinEmpresa.Checked = this.applicationInfo.RequiereLoginSinEmpresa;
            this.txtDominio.Text = this.applicationInfo.Domain;
            this.txtPathAd.Text = this.applicationInfo.AdPath;
            this.txtUsuarioAd.Text = this.applicationInfo.AdUser;
            this.txtContacto.Text = this.applicationInfo.Contacto;
            
            this.txtNombre.Text = applicationInfo.Name;
            this.txtUrl.Text = applicationInfo.Url;            

            this.GridRoles.DataSource = applicationInfo.Roles;
            this.GridRoles.DataBind();

            this.GridOperaciones.DataSource = applicationInfo.Operations;
            this.GridOperaciones.DataBind();
        }

        private void SetData()
        {
            applicationInfo.Id = Convert.ToInt32(this.txtCodigo.Text);
            applicationInfo.Name = this.txtNombre.Text;
            applicationInfo.Url = this.txtUrl.Text;
            applicationInfo.RequiereLoginSinEmpresa = this.chkRequireLoginSinEmpresa.Checked;
            applicationInfo.Contacto = this.txtContacto.Text;

            this.applicationInfo.AdPath = this.txtPathAd.Text;
            this.applicationInfo.AdUser = this.txtUsuarioAd.Text;
            this.applicationInfo.Domain = this.txtDominio.Text;
            if (!String.IsNullOrEmpty(this.txtPasswordAd.Text))
            {
                this.applicationInfo.AdPassword = this.txtPasswordAd.Text;
            }
        }

        private void Save()
        {
            Validar();
            SetData();
            this.applicationInfo = WebServiceHelper.SaveApplication(this.applicationInfo);
            Bind();
        }

        private void Validar()
        {
            // TODO
        }


        protected void lnkGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                Save();                
                this.Response.Redirect("/App/ApplicationList.aspx");
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkAgregarRole_Click(object sender, EventArgs e)
        {
            try
            {
                this.Response.Redirect(string.Format("/App/RoleEdit.aspx?applicationId={0}", applicationInfo.Id), true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkAgregarOperacion_Click(object sender, EventArgs e)
        {
            try
            {
                this.Response.Redirect(string.Format("/App/OperationCreate.aspx?applicationId={0}", applicationInfo.Id), true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridRoles_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "editar")
                {
                    int roleId = Convert.ToInt32(this.GridRoles.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    this.Response.Redirect(string.Format("/App/RoleEdit.aspx?Id={0}&applicationId={1}", roleId, applicationInfo.Id), true);
                }
                else if(e.CommandName == "eliminar")
                {
                    int roleId = Convert.ToInt32(this.GridRoles.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    WebServiceHelper.DeleteRole(applicationInfo.Id, roleId);
                    applicationInfo = WebServiceHelper.GetApplicationById(Convert.ToInt32(this.Request.QueryString["Id"]));
                    Bind();
                }               
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridRoles_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                //if (e.Row.RowType == DataControlRowType.DataRow)
                //{
                //    RoleIncluded operation = (RoleIncluded)e.Row.DataItem;

                //    LinkButton lnkRowVerRoles = (LinkButton)e.Row.Cells[4].FindControl("lnkRowVerRoles");
                //    lnkRowVerRoles.CommandArgument = e.Row.RowIndex.ToString();
                //}
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridOperaciones_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    OperationIncluded operation = (OperationIncluded)e.Row.DataItem;

                    LinkButton lnkRowVerRol = (LinkButton)e.Row.Cells[5].FindControl("lnkRowVerRol");
                    lnkRowVerRol.CommandArgument = e.Row.RowIndex.ToString();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
       
        protected void GridOperaciones_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "eliminar")
                {
                    int operationId = Convert.ToInt32(this.GridOperaciones.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    WebServiceHelper.DeleteOperation(operationId);
                    applicationInfo = WebServiceHelper.GetApplicationById(Convert.ToInt32(this.Request.QueryString["Id"]));
                    Bind();
                }
                if (e.CommandName == "editar")
                {
                    int operationId = Convert.ToInt32(this.GridOperaciones.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    this.Response.Redirect(string.Format("/App/OperationCreate.aspx?Id={0}", operationId), true);
                }
                else if (e.CommandName == "verroles")
                {
                    int operationId = Convert.ToInt32(this.GridOperaciones.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    this.Response.Redirect(string.Format("/App/OperationViewRoles.aspx?Id={0}", operationId, true));
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void verUsuariosButton_Click(object sender, EventArgs e)
        {
            try
            {
                 this.Response.Redirect(string.Format("/App/UserList.aspx?applicationId={0}", this.applicationInfo.Id), true);             
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkCrearUsuario_Click(object sender, EventArgs e)
        {
            try
            {
                if (applicationInfo != null)
                {
                    this.Response.Redirect(string.Format("/App/UserEdit.aspx?Application={0}", applicationInfo.Id), true);
                }
                else
                {
                    this.masterPage.ShowMessage("Para crear un usuario debe estar en el contexto de una aplicación", WebMessageType.Notification);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}